﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

/// <summary>
/// 绵羊模板
/// </summary>
public class SheepModule : MonoBehaviour
{

    public float animationDelaytime;
    private float startTime;
    private bool canweStartAnim
    {
        get { return Time.realtimeSinceStartup - startTime > animationDelaytime; }
    }
    
    private AnimatorStateInfo info
    {
        get {
            return anim.GetCurrentAnimatorStateInfo(0);
        }
    }
    

    //点击事件判定时间间隔
    public float clickDeltaTime = 0.08f;

    //一次鼠标[按下-抬起]事件鼠标移动的距离
    public float mouseMoveDistance = 0f;

    private HerdSheep manager;
    
    private RoomLimit roomLimit;

    private CutSheepFeather cutsheepfeather;

    private SheepType sheepType;

    private GameObject sheepBody;

    private GameObject sheepFeather;
    
    private Vector3 fisrtPosition;
    private Vector3 lastPosiiotn;

    private Camera cacheCamera;

    private bool IsInFold = false;
    private bool LockMouseEvent = false;

    private Animator anim;

    private GameObject miemieEffect;//气泡
    private GameObject rippleEffect;//波纹

    private GameObject growupEffect;//长毛
    private GameObject dropEffect;//掉毛

    private GameObject featherSpawnPos;

    //供赶羊初始化
    public void Set(SheepType t,Vector3 spawnPos,HerdSheep m, RoomLimit rl,float delay,bool infold = false)
    {
        manager = m;
        sheepType = t;
        fisrtPosition = spawnPos;
        lastPosiiotn = spawnPos;
        IsInFold = infold;

        roomLimit = rl;

        Init(delay);
    }

    //供剪羊毛初始化
    public void Set(SheepType t, Vector3 spawnPos, CutSheepFeather csf,float delay)
    {
        cutsheepfeather = csf;
        sheepType = t;
        fisrtPosition = spawnPos;
        lastPosiiotn = spawnPos;
        IsInFold = false;

        Init(delay);
    }
    
    private void Init(float delay)
    {
        startTime = Time.realtimeSinceStartup;
        animationDelaytime = delay;
        //Debug.Log(animationDelaytime);

        anim = GetComponent<Animator>();
        Material gray;
        Material white;
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.grayMaterial, typeof(Material), enResourceType.Prefab);
        gray = new Material(r.m_content as Material);
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.whiteMaterial, typeof(Material), enResourceType.Prefab);
        white = new Material(r.m_content as Material);
        sheepBody = transform.Find("303030201").gameObject;
        sheepFeather = transform.Find("303030202").gameObject;
        miemieEffect = transform.Find("popEffect").gameObject;
        rippleEffect = transform.Find("rippleEffect").gameObject;
        string houzui;
        if (sheepType == SheepType.graySheepClean || sheepType == SheepType.graySheepWithFeather)
            houzui = "_g";
        else
            houzui = "_w";
        growupEffect = transform.Find("featherGrowup"+houzui).gameObject;
        dropEffect = transform.Find("featherDrop"+houzui).gameObject;
        featherSpawnPos = transform.Find("featherSpawn").gameObject;
        switch (sheepType)
        {
            case SheepType.graySheepClean:
                sheepBody.GetComponent<SkinnedMeshRenderer>().material = gray;
                sheepFeather.SetActive(false);
                break;
            case SheepType.graySheepWithFeather:
                sheepBody.GetComponent<SkinnedMeshRenderer>().material = gray;
                sheepFeather.GetComponent<SkinnedMeshRenderer>().material = gray;
                break;
            case SheepType.whiteSheepClean:
                sheepBody.GetComponent<SkinnedMeshRenderer>().material = white;
                sheepFeather.gameObject.SetActive(false);
                break;
            case SheepType.whiteSheepWithFeather:
                sheepBody.GetComponent<SkinnedMeshRenderer>().material = white;
                sheepFeather.GetComponent<SkinnedMeshRenderer>().material = white;
                break;

        }

        transform.position = fisrtPosition;
        cacheCamera = GameObject.FindObjectOfType<Camera>();
    }

    public void HideEffect()
    {
        rippleEffect.SetActive(false);
        miemieEffect.SetActive(false);
    }

    public void ShowBoWen()
    {
        rippleEffect.SetActive(true);
    }

    public void HideBoWen()
    {
        if(rippleEffect.activeInHierarchy)
        rippleEffect.SetActive(false);
    }

    public void ShowQipao()
    {
        miemieEffect.SetActive(true);
    }



    private void Update()
    {
        if (miemieEffect != null && miemieEffect.activeInHierarchy)
        {
            miemieEffect.transform.LookAt(cacheCamera.transform);
        }

        if (canweStartAnim)
        {
            if (info.normalizedTime >= 0.99f)
            { 
                int state = anim.GetInteger("state");
                int nextState = MathHelp.GetNumbersExcept(new List<int> { 0, 1, 2 }, state);
                anim.SetInteger("state",nextState);
            }
        }
    }

    //剪羊毛
    private void CutFeather(Action action)
    {
        //1.播放特效 羊毛脱落
        //2.羊毛隐藏
        sheepFeather.SetActive(false);
        dropEffect.SetActive(true);
        ParticleSystem p1 = dropEffect.GetComponentInChildren<ParticleSystem>();
        float time1 = p1.duration+p1.startDelay + p1.startLifetime;
        TimerManager.Instance.AddTimer(time1, action);
        TimerManager.Instance.AddTimer(time1 + 1f, FeatherGrowup);
    }

    private void DisplayFeatherAdd()
    {
        HUIEvent hUIEvent = new HUIEvent();
        hUIEvent.m_eventID = enUIEventID.AddPlus_SheepFeather_Cuted;
        hUIEvent.m_eventParams.argInt = (int)sheepType;
        hUIEvent.m_eventParams.argString = string.Format("{0},{1},{2}", 
            featherSpawnPos.transform.position.x,
            featherSpawnPos.transform.position.y,
            featherSpawnPos.transform.position.z);
        HUIEventManager.Instance.DispatchUIEvent(hUIEvent);
    }

    //羊毛生长
    private void FeatherGrowup()
    {
        //1.有羊毛吗?
        //2.没有就长羊毛
        if (!IsSheepHasFeather())
        {
            dropEffect.SetActive(false);
            anim.CrossFade(TenPlusModuleAssetPath.anim_sheep_eat,TenPlusAnimLength.animationCrossTime);
            growupEffect.SetActive(true);
            TimerManager.Instance.AddTimer(4f,()=> 
            {
                sheepFeather.SetActive(true);
            });
        }
    }

    //绵羊有毛吗？
    public bool IsSheepHasFeather()
    {
        return sheepFeather.activeInHierarchy;
    }


    private MouseEventType lastMouseEvent = MouseEventType.none;

    private void OnMouseDrag()
    {
        if (IsInFold || LockMouseEvent) return;
        if (manager == null) return;
        if (lastMouseEvent == MouseEventType.MouseDown)
        {
            if (Vector2.Distance(clickPoint, new Vector2(Input.mousePosition.x, Input.mousePosition.y)) > 2f)
                lastMouseEvent = MouseEventType.MouseDrag;
        }
        else
        {
            Vector3 newDrag;
            //1.物体世界坐标转为屏幕坐标
            newDrag = cacheCamera.WorldToScreenPoint(transform.position);
            //2.记录鼠标平移的偏移量
            newDrag = new Vector3(Input.mousePosition.x, Input.mousePosition.y, newDrag.z);
            //3.屏幕坐标转为世界坐标
            newDrag = cacheCamera.ScreenToWorldPoint(newDrag);


            Vector3 afterLimitPos = newDrag;
            //roomLimit.LimitPointInThisRoom(newDrag,maxz, minz, out afterLimitPos);
            float foldY = fisrtPosition.y + manager.foldHeight;
            bool flag = false;
            if (manager.currentFoldNum == 1)
            {
                roomLimit.LimitPointInThisRoom(newDrag, manager.onefold.theLimitArea, foldY, out afterLimitPos);
                flag = true;
            }
            else
            {
                if (MathHelp.IsPointInRect(newDrag, manager.twofold2.theLimitArea) == -1)
                {
                    roomLimit.LimitPointInThisRoom(newDrag, manager.twofold2.theLimitArea, foldY, out afterLimitPos);
                    flag = true;
                }

                if (MathHelp.IsPointInRect(newDrag, manager.twofold1.theLimitArea) == -1)
                {
                    roomLimit.LimitPointInThisRoom(newDrag, manager.twofold1.theLimitArea, foldY, out afterLimitPos);
                    flag = true;
                }
            }

            if (flag)
                roomLimit.LimitPointInThisRoom(afterLimitPos, out afterLimitPos);
            else
                roomLimit.LimitPointInThisRoom(newDrag, out afterLimitPos);
            transform.position = afterLimitPos;
            lastPosiiotn = transform.position;
            lastMouseEvent = MouseEventType.MouseDrag;
        }
    }

    Vector2 clickPoint;
    float lastMouseDownTime;
    float lastShoutTime;
    private void OnMouseDown()
    {
        if (LockMouseEvent) return;
        lastMouseEvent = MouseEventType.MouseDown;
        clickPoint = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
        lastMouseDownTime = Time.realtimeSinceStartup;
    }

    private void OnMouseUp()
    {
        /*
         赶羊游戏中响应点击和拖动事件
         剪羊毛游戏中只响应点击事件
         */
        DispatchUpdateTime();
        if (LockMouseEvent) return;
        lastMouseEvent = MouseEventType.MouseUp;
        if (Time.realtimeSinceStartup - lastMouseDownTime < clickDeltaTime)
        {
            //点击
            if (manager == null)
            {
                Debug.Log("剪羊毛点击事件");
                HideBoWen();
                if (IsSheepHasFeather())
                {
                    //剪羊毛
                    if (cutsheepfeather.CanyouCutSheepFeather((int)sheepType))
                    {
                        //
                        CutFeather(DisplayFeatherAdd);
                    }
                    else
                    {
                        //这种羊毛我们已经剪够了，去剪另外一种羊毛吧！
                        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030205);
                    }
                }
                else
                {
                    //咩咩叫
                    SheepShout();
                    //这只剪过了，我们换一只吧
                    AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030203);
                }

            }
            else
            {
                //赶羊
                //绵羊咩咩叫
                if (Time.realtimeSinceStartup - lastShoutTime > 1.5f)//控制点击频率
                {
                    SheepShout();
                    //DispatchShepShout(Vector3.zero);
                    lastShoutTime = Time.realtimeSinceStartup;
                }
            }
        }
        else
        {
            //拖拽
            if (IsInFold) return;
            if (manager == null)
            {
                //剪羊毛场景无拖拽
            }
            else
            {
                //松手检测
                //1.在羊圈内 2.羊的颜色正确

                Vector3 legalPos;
                if (!manager.SheepEnterFoldTest((int)sheepType, transform.position, gameObject, fisrtPosition.y, out legalPos))
                {
                    //移回去
                    transform.DOMove(fisrtPosition, 0.6f);
                }
                else
                {
                    //入圈
                    IsInFold = true;
                    //SheepShout();
                    //DispatchShepShout(legalPos);
                    manager.SheepEnterFold((int)sheepType, transform.position, gameObject, fisrtPosition.y);
                }

            }
        }
        
    }

    public void LockClick()
    {
        LockMouseEvent = true;
    }

    void SheepShout()
    {
        anim.CrossFade(TenPlusModuleAssetPath.anim_sheep_speak, TenPlusAnimLength.animationCrossTime);
        AudioClip clip = AudioManager.Instance.GetAudioClip(TenPlusModuleAssetPath.audio_603030101);
        if (!AudioManager.Instance.IsPlayingSoundClip(clip))
        {
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_603030101);
        }
        if (manager != null)
        {
            miemieEffect.SetActive(true);
            TimerManager.Instance.AddTimer(2f, () =>
             {
                 miemieEffect.SetActive(false);
             });
        }
    }

    void DispatchUpdateTime()
    {
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.AddPlus_UpdateOperateTime);
    }

    void DispatchShepShout(Vector3 pos)
    {
        HUIEvent hUIEvent = new HUIEvent();
        hUIEvent.m_eventID = enUIEventID.AddPlus_SheepShout;
        Vector2 screenPoint = cacheCamera.WorldToScreenPoint(transform.position).Vector3ToVector2_XY();
        Vector2 screenPoint2 = cacheCamera.WorldToScreenPoint(pos).Vector3ToVector2_XY();
        hUIEvent.m_eventParams.argString = string.Format("{0},{1}", screenPoint.x, screenPoint.y);
        if (pos != Vector3.zero)
            hUIEvent.m_eventParams.argString2 = string.Format("{0},{1}", screenPoint2.x, screenPoint2.y);
        else
            hUIEvent.m_eventParams.argString2 = "";
        HUIEventManager.Instance.DispatchUIEvent(hUIEvent);
    }
}

//绵羊种类
public enum SheepType
{
    whiteSheepClean = 1,
    whiteSheepWithFeather = 2,
    graySheepClean = 3,
    graySheepWithFeather = 4
}


//鼠标事件类型
public enum MouseEventType
{
    none,
    MouseDown,
    MouseUp,
    MouseDrag,
}

